package com.beamfield.common;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

/**
 * 不同时间类型之间的转换
 * 
 * @author mintonzhang@163.com
 * @date 2018年6月8日
 */
public class DateSwitcher {

	private static final String[] DATE_FORMAT = { "yyyy-MM-dd HH:mm:ss", "yyyyMMddHHmmss", "yyyy-MM-dd", "yyyyMMdd",
			"yyyy-MM-dd HH:mm" };

	public static String transform2Standard(String origin) {
		try {
			Date tmp = string2Date(origin);
			return date2String(tmp, 0);
		} catch (Exception e) {
		}
		return origin;
	}

	public static String transform2Standard(String origin, String format) {
		try {
			if (StringUtils.isNotBlank(format)) {
				Date tmp = DateUtils.parseDate(origin, Locale.CHINA, format);
				return date2String(tmp, 0);
			}
		} catch (Exception e) {
		}
		transform2Standard(origin);
		return origin;
	}

	public static String transform(String origin, String formatTo) {
		try {
			Date tmp = string2Date(origin);
			return date2String(tmp, formatTo);
		} catch (Exception e) {
		}
		return origin;
	}

	public static String date2String(Date date) {
		return date2String(date, "yyyy-MM-dd HH:mm:ss");
	}

	public static String date2String(Date date, int formatIndex) {
		return DateFormatUtils.format(date, DATE_FORMAT[formatIndex], TimeZone.getTimeZone("GMT+8"));
	}

	public static String date2String(Date date, String format) {
		return DateFormatUtils.format(date, format, TimeZone.getTimeZone("GMT+8"));
	}

	public static Date string2Date(String source) throws ParseException {
		return DateUtils.parseDate(source, Locale.CHINA, DATE_FORMAT);
	}

	public static String long2DateStr(long source) {
		return long2DateStr(source, "yyyy-MM-dd HH:mm:ss");
	}

	public static String long2DateStr(long source, int formatIndex) {
		return DateFormatUtils.format(new Date(source), DATE_FORMAT[formatIndex], TimeZone.getTimeZone("GMT+8"));
	}

	public static String long2DateStr(long source, String format) {
		return DateFormatUtils.format(new Date(source), format, TimeZone.getTimeZone("GMT+8"));
	}

	public static Date long2Date(long source) {
		return new Date(source);
	}

	public static int getMinutesFromDayBegin(Date date) {
		long msSet = date.getTime();
		Calendar dayBegin = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
		dayBegin.setTime(date);
		dayBegin.set(Calendar.HOUR_OF_DAY, 0);
		dayBegin.set(Calendar.MINUTE, 0);
		dayBegin.set(Calendar.SECOND, 0);
		dayBegin.set(Calendar.MILLISECOND, 0);
		long msBegin = dayBegin.getTimeInMillis();
		int minutesFromDayBegin = (int) ((msSet - msBegin) / (60 * 1000));
		return minutesFromDayBegin;
	}

	public static int getMinutesFromDayBegin(String time) {
		assert time != null;
		int hour = 0;
		int minute = 0;
		String[] hm = time.split(":");
		hour = Integer.valueOf(hm[0]);
		if (time.indexOf(":") != -1) {
			String m = hm[1];
			if (m.startsWith("0")) {
				m = m.substring(0);
			}
			minute = Integer.valueOf(m);
		}
		Calendar daySet = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
		daySet.set(Calendar.HOUR_OF_DAY, hour);
		daySet.set(Calendar.MINUTE, minute);
		daySet.set(Calendar.SECOND, 0);
		daySet.set(Calendar.MILLISECOND, 0);
		long msSet = daySet.getTimeInMillis();

		Calendar dayBegin = Calendar.getInstance();
		dayBegin.set(Calendar.HOUR_OF_DAY, 0);
		dayBegin.set(Calendar.MINUTE, 0);
		dayBegin.set(Calendar.SECOND, 0);
		dayBegin.set(Calendar.MILLISECOND, 0);
		long msBegin = dayBegin.getTimeInMillis();
		int minutesFromDayBegin = (int) ((msSet - msBegin) / (60 * 1000));
		return minutesFromDayBegin;
	}

	/**
	 * 根据日期字符串格式化为指定的日期
	 * 
	 * @author minton
	 * @email mintonzhang@163.com
	 * @date 2018年5月24日
	 * @param source
	 * @param format
	 * @return
	 */
	public static Date string2Date(String source, String format) {
		if (StringUtils.isBlank(format)) {
			format = DATE_FORMAT[0];
		}
		try {
			return DateUtils.parseDate(source, format);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 比较两个时间的大小
	 * 
	 * @author minton
	 * @email mintonzhang@163.com
	 * @date 2018年5月24日
	 * @param date1
	 *            字符串或者时间
	 * @param date2
	 *            字符串或者时间
	 * @return -1为报错或者数据有误 1 为前者比后者大或者相等 相反为0
	 * @throws ParseException
	 */
	public static Integer compareDate(Object date1, Object date2) {
		try {
			Date d1 = date1 instanceof Date ? (Date) date1
					: date1 instanceof String ? string2Date((String) date1) : null;
			Date d2 = date2 instanceof Date ? (Date) date2
					: date2 instanceof String ? string2Date((String) date2) : null;
			if (d1 == null || d2 == null) {
				return -1;
			}
			int r = d1.before(d2) ? 0 : 1;
			return r;
		} catch (ParseException e) {
			e.printStackTrace();
			return -1;
		}
	}

	/**
	 * 得到一个月份的最大天数
	 * 
	 * @author minton
	 * @email mintonzhang@163.com
	 * @date 2018年5月25日
	 * @param date
	 * @return
	 */
	public static Integer getMaxDayOfMonth(Object date) {
		try {
			Date d1 = date instanceof Date ? (Date) date
					: date instanceof String ? string2Date(dateCheck((String) date)) : null;
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(d1);
			// 初始化为1号
			calendar.set(Calendar.DAY_OF_MONTH, 1);
			return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
		} catch (ParseException e) {
			e.printStackTrace();
			return -1;
		}
	}

	/**
	 * 时间校验 默认为 - 截取
	 * 
	 * @author minton
	 * @email mintonzhang@163.com
	 * @date 2018年5月25日
	 * @param s
	 * @return
	 */
	private static String dateCheck(String s) {
		String[] date = s.split("-");
		date[date.length - 1] = "1";
		return String.join("-", date);
	}

	/**
	 * 判断两个时间字符串是否相等
	 * 
	 * @date 2018年6月14日
	 * @author mintonzhang@163.com
	 * @param date1 时间字符串 或 Date
	 * @param date2 时间字符串或Date
	 * @param 格式化模式
	 * @return
	 */
	public static boolean isSameDate(Object date1, Object date2, String format) {
		if (StringUtils.isBlank(format)) {
			format = DATE_FORMAT[2];
		}
		try {
			String date1Str = date1 instanceof Date ? date2String((Date) date1, format)
					: date1 instanceof String ? transform(date1.toString(), format) : null;
			String date2Str = date2 instanceof Date ? date2String((Date) date2, format)
					: date2 instanceof String ? transform(date2.toString(), format) : null;
			return date1Str.equals(date2Str) ? true : false;

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public static void main(String[] args) {
		
		System.out.println(isSameDate(new Date(),"2018-06-14 13:40", "yyyy-MM-dd HH:mm"));
		
		// String[] s = "2018-2-99".split("-");
		// System.out.println(dateCheck("2018-2--1"));
		// for (String string : s) {
		// System.out.println(string);
		//// }
		// System.out.println(getMaxDayOfMonth("2020-2"));
		// Date now = new Date();
		// if (DateSwitcher.compareDate(now, "2018-5-24 23:59:59") != 1
		// || DateSwitcher.compareDate(now, "2018-5-23 23:59:59") != 1) {
		// System.out.println("1");
		// } else {
		// System.out.println("2");
		// }
		// // int a = DateSwitcher.getMinutesFromDayBegin("23:11");
		// // String a = DateSwitcher.long2DateStr(1510876800000L);
		// // System.out.println(a);
		// // System.setProperty("user.timezone","Asia/Shanghai");
		// // Calendar dayBegin = Calendar.getInstance();
		// // System.out.println(dayBegin.getTimeInMillis());
		// // System.out.println(new Date().getTime());
		// System.out.println("23：50".matches("([01]\\d|2[0-4])[:|：][0-5]\\d"));
		// ;
		// // try {
		// // String date = "2017-10-23";
		// // Date tmp = DateSwitcher.string2Date(date);
		// // System.out.println(DateSwitcher.date2String(tmp));
		// // String result = transform(date,"yyyy-MM");
		// // System.out.println(result);
		// // } catch (ParseException e) {
		// // e.printStackTrace();
		// // }
		// //
		// // final String[] scheduleColor = { "rgb(97, 144, 232)",
		// // "rgb(120, 164, 250)",
		// // "rgb(19, 206, 102)",
		// // "rgb(255, 200, 44)",
		// // "rgb(255, 73, 73)",
		// // "rgb(194, 171, 199)",
		// // "rgb(191, 191, 191)",
		// // "rgb(240, 208, 213)",
		// // "rgb(44, 64, 90)" };
		// // Random rd = new Random();
		// // System.out.println(scheduleColor[rd.nextInt(scheduleColor.length)]);
		// // //schedule.setScheduleColor(scheduleColor[rd.nextInt()]);//随机颜色
		//
		// // String timeReg = "(\\d{1}|[01]\\d|2[0-4]):[0-5]\\d";
		// //
		// // System.out.println("0:00".matches(timeReg));
		// Calendar calendar = Calendar.getInstance();
		// System.out.println(calendar.get(Calendar.YEAR) + 1);
		//
		// System.err.println(String.format("%02d", Integer.valueOf("10")));
		// // System.out.println(calendar.getTimeInMillis()/60000);
		// // calendar = Calendar.getInstance();
		// // calendar.set(Calendar.DAY_OF_MONTH, 1);
		// // System.out.println(calendar.getTimeInMillis()/60000);
		//
		// // calendar.getTime().before(calendar2.getTime());
		// // System.out.println(calendar.getTime().before(calendar2.getTime()));
		// //
		// // System.out.println(calendar2.getTime().getTime());
		// // System.out.println(DateSwitcher.date2String(calendar.getTime(),
		// "yyyy-MM-dd")
		// // );
		//
//		Long l = 56669224L;
//		Number overD = ((double) l % (1000 * 60 * 60 * 24) / (1000 * 60 * 60));
//
//		// System.out.println(String.format("%.2f", overD));
//		System.out.println(overD);
//		NumberFormat nf = NumberFormat.getNumberInstance();
//		// 保留两位小数
//		nf.setMaximumFractionDigits(2);
//
//		// 如果不需要四舍五入，可以使用RoundingMode.DOWN
//		nf.setRoundingMode(RoundingMode.UP);
//
//		System.out.println(nf.format(overD));
		// /
	}

}
